/**
 * @FileName: SkuService.java
 * @Author 熊诗言
 * @Description:
 * @Date 2016年4月18日 下午2:44:11
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service.product;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.model.product.Sku;
import cn.hpclub.server.model.product.SkuOpt;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.QueryHelper;

public class SkuService{

    public static final SkuService service = new SkuService();

    /**
     * @Title: getQueryHelper
     * @Description:获取查询列表的helper
     * @param searchInfo
     * @return QueryHelper
     */

    public QueryHelper getQueryHelper(ConcurrentHashMap<String, String> searchInfo){
        // System.out.println(searchInfo.containsKey("name"));
        QueryHelper helper = new QueryHelper(
                "select k.id,k.name,k.sort,s.user_name as operated_by,k.operated_time,k.enabled",
                "sku k left join sys_user s on k.operated_by=s.id")//
                        .addCondition(searchInfo.containsKey("name"),
                                      "(k.name like ? or k.id in (select o.sku_id from sku_opt o where o.name like ?))",
                                      "%" + searchInfo.get("name") + "%", "%" + searchInfo.get("name") + "%")
                        .addCondition("k.enabled=?", 1)//
                        .addOrderProperty("k.sort", true).addOrderProperty("k.operated_time", false);

        return helper;
    }

    /**
     * @Title: getOptsById
     * @Description:获取本sku的opts
     * @param id
     * @param searchInfo
     * @return List<Skuopt>
     */

    public Page<SkuOpt> getOptsById(int pageNumber, int pageSize, String id,
            ConcurrentHashMap<String, String> searchInfo){
        QueryHelper helper = new QueryHelper("select o.id,o.name,s.user_name as operated_by,o.operated_time,o.enabled",
                "sku_opt o left join sys_user s on o.operated_by=s.id")//
                        .addCondition("o.sku_id=?", id)//
                        .addCondition(searchInfo.containsKey("name"), "o.name like ?",
                                      "%" + searchInfo.get("name") + "%")
                        .addCondition("o.enabled=?", 1)//
                        .addOrderProperty("o.operated_time", false);
        Page<SkuOpt> pager = SkuOpt.dao.paginate(pageNumber, pageSize, helper.getSelect(), helper.getSqlExceptSelect());
        return pager;
    }

    /**
     * @Title: changeStatus
     * @Description:改变状态
     * @param id
     * @param targetStatus
     * @return boolean
     */
    public boolean changeStatus(String id, String targetStatus){
        String sql = "";
        if("1".equalsIgnoreCase(targetStatus)){
            sql = "update sku set enabled = 1 where id=?";
        } else{
            sql = "update sku set enabled = 0 where id=?";
        }

        return Db.update(sql, id) > 0;
    }

    /**
     * @Title: saveOrUpdate
     * @Description:保存或者更新一个Sku
     * @param sku
     * @param optMap
     * @param userId
     * @param isAdd
     */

    public void saveOrUpdate(Sku sku, String[] optNames, Map<String, String> optMap, boolean isAdd){
        if(isAdd){
            // 先保存sku
            sku.save();
            // 保存所有的opt
            int skuId = sku.getInt("id");
            insertOptWithSku(optNames, skuId);
        } else{
            // 先更新sku
            sku.update();
            int skuId = sku.getInt("id");
            // 更新以前的
            updateOpts(optMap);
            // 添加现在的
            insertOptWithSku(optNames, skuId);
        }
    }

    /**
     * @Title: updateOpts
     * @Description:更新map中的opt，map的key为id，value为name
     * @param optMap
     */

    private void updateOpts(Map<String, String> optMap){
        Date now = new Date();
        int userId = InterfaceUtil.getAdminId();
        SkuOpt opt;
        for(Entry<String, String> entry : optMap.entrySet()){
            opt = SkuOpt.dao.findById(entry.getKey());
            opt.set(SkuOpt.NAME, entry.getValue())//
                    .set(SkuOpt.OPERATED_BY, userId)//
                    .set(SkuOpt.OPERATED_TIME, now).update();
        }
    }

    /**
     * @Title: insertOptWithSku
     * @Description:插入sku相关的opt
     * @param optNames
     * @param now
     * @param userId
     * @param skuId
     */

    private void insertOptWithSku(String[] optNewNames, int skuId){
        if(optNewNames == null){
            return;
        }
        Date now = new Date();
        int userId = InterfaceUtil.getAdminId();
        for(String optName : optNewNames){
            new SkuOpt().set(SkuOpt.NAME, optName)//
                    .set(SkuOpt.SKU_ID, skuId)//
                    .set(SkuOpt.OPERATED_BY, userId)//
                    .set(SkuOpt.OPERATED_TIME, now).set(SkuOpt.ENABLED, 1)//
                    .save();
        }
    }

    /**
     * @Title: saveOrUpdate
     * @Description:保存或者更新一个sku_opt
     * @param skuopt
     * @param isAdd
     */

    public void saveOrUpdate(SkuOpt skuopt, boolean isAdd){
        if(isAdd){
            skuopt.save();
        } else{
            skuopt.update();
        }
    }

    /**
     * @Title: changeOptStatus
     * @Description:TODO
     * @param id
     * @param targetStatus
     * @return boolean
     */

    public boolean changeOptStatus(String id, String targetStatus){
        String sql = "";
        if("1".equalsIgnoreCase(targetStatus)){
            sql = "update sku_opt set enabled = 1 where id=?";
        } else{
            sql = "update sku_opt set enabled = 0 where id=?";
        }

        return Db.update(sql, id) > 0;
    }

    /**
     * @Title: deleteByIds
     * @Description:删除attr_set_sku表中sku_id的相关记录
     * @param ids
     */

    public void deleteByIds(Integer[] ids){
        if(ids == null || ids.length == 0){
            return;
        }
        for(Integer sku_id : ids){
            deleteBySkuId(sku_id);
        }
    }

    /**
     * @Title: deleteBySkuId
     * @Description:删除attr_set_sku表中sku_id的相关记录
     * @param sku_id
     */

    private void deleteBySkuId(int sku_id){
        // 1.先找到这些记录
        List<Record> records = Db.find("select * from attr_set_sku a where a.sku_id=?", sku_id);
        // 2.删除这些记录
        for(Record record : records){
            Db.delete("attr_set_sku", record);
        }
    }

    /**
     * @Title: deleteSkuoptBySku
     * @Description:删除sku_opt中的sku相关记录
     * @param ids
     */

    public void deleteSkuoptBySku(Integer[] ids){
        StringBuffer idBuf = new StringBuffer("");
        String idStr = "";
        if(null != ids && ids.length != 0){
            for(Integer id : ids){
                idBuf.append(id).append(",");
            }
            idStr = idBuf.toString();
            idStr = idStr.substring(0, idStr.lastIndexOf(","));
        }

        String sql = "select * from sku_opt o where o.sku_id in(" + idStr + ")";
        List<SkuOpt> skuopts = SkuOpt.dao.find(sql);
        for(SkuOpt skuopt : skuopts){
            skuopt.delete();
        }
    }

    /**
     * @Title: getSkuInfoByAttrSetId
     * @Description:根据分类对应的属性集ID获取商品可选sku和skuopt信息
     * @param attrsetid
     * @return List<Record>
     */
    public List<Record> getSkuInfo(){
        String sql = "select sku.id as skuid,sku.name as skuname from sku where sku.enabled=1";
        List<Record> attrSets = Db.find(sql);
        for(Record r : attrSets){
            String skuSql = "select id,name,code from sku_opt where enabled=1 and sku_id=?  ORDER BY id ASC";
            List<SkuOpt> skuOpts = SkuOpt.dao.find(skuSql, r.getInt("skuid"));
            r.set("opts", skuOpts);
        }

        return attrSets;
    }

}
